 GET TimLib:hdr.System
 GET TimLib:hdr.Macros
 GET TimLib:hdr.Division
 GET TimLib:hdr.Streams
 GET TimLib:hdr.SeqF
 GET hdr.MemUtils

 EXPORT Channel_FillMonitorBuffer

 ; default area assignment

 AREA |Assembler|,READONLY,CODE

;-------------------------------------------------------------------------------
; Channel_FillMonitorBuffer
;
; In  - [R0+&00] glbmem ptr
;       [R0+&04] mixstream ptr
;       [R0+&08] buffer ptr or 0
;       [R0+&0C] buffer len (bytes)
;
; Out - [R0+&10] buffer peak value [0, &7FFF]
;       [R0+&14] buffer mean value [0, &7FFF]
;-------------------------------------------------------------------------------
 ALIGN

Channel_FillMonitorBuffer
 _DEFPROC "R0-R11"
 MOV     R11,R0
 LDR     R12,[R11,#0]
 LDR     R7,[R11,#4]
 LDR     R0,[R11,#8]
 LDR     R1,[R11,#12]
 BL      Note_FillMonitorBuffer
 STR     R4,[R11,#16]
 STR     R5,[R11,#20]
 _ENDPROC

;-------------------------------------------------------------------------------
; Note_FillMonitorBuffer
;
; In  - R0  16-bit buffer ptr or 0
;       R1  buffer len (bytes)
;       R7  mixstream ptr
;       R12 glbmem ptr
;
; Out - R4  buffer peak value [0, &7FFF]
;       R5  buffer mean value [0, &7FFF]
;-------------------------------------------------------------------------------
 ALIGN

Note_FillMonitorBuffer
 _DEFPROC "R0-R2,R6,R8-R11"

 MOV     R4,#0
 MOV     R5,#0

 CMP     R7,#0
 BEQ     Notes_FillMonitorBuffer_Clear

 LDR     R9,[R7,#stream_pbuffer]
 CMP     R9,#0
 BEQ     Notes_FillMonitorBuffer_Clear

 MOV     R10,R0
 BL      Seq_GetSampleSize
 MOV     R8,R0
 MOV     R0,R10
 MOV     R8,R8,LSL #1
 CMP     R0,#0
 CMPHI   R8,R1
 MOVHI   R8,R1
 CMP     R8,#0
 BEQ     Notes_FillMonitorBuffer_Clear
 ADD     R10,R9,R8

 ; Loop on buffer to get peak and mean value
 ; and scale with channel volume

Note_FillMonitorBuffer_BufLoop
 LDR     R14,[R9],#4
 MOV     R6,R14,LSR #16
 MOV     R11,R14,LSL #16
 MOV     R11,R11,LSR #16
 CMP     R0,#0
 STRNE   R14,[R0],#4
 TST     R11,#&8000
 RSBNE   R11,R11,#&10000
 CMP     R4,R11
 MOVLO   R4,R11
 ADD     R5,R5,R11
 TST     R6,#&8000
 RSBNE   R6,R6,#&10000
 CMP     R4,R6
 MOVLO   R4,R6
 ADD     R5,R5,R6
 CMP     R9,R10
 BLO     Note_FillMonitorBuffer_BufLoop

 ; Compute mean value

 SUBS    R1,R1,R8
 MOVLT   R1,#0
 MOV     R8,R8,LSR #1
 _DIVIDE R11,R5,R8,R6
 MOV     R5,R11

Notes_FillMonitorBuffer_Clear
 CMP     R0,#0
 BLNE    Mem_Clear

 _ENDPROC

 END
